package com.ruoyi.kenuo.netty;

import com.alibaba.fastjson2.JSON;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.internal.StringUtil;

import java.util.concurrent.TimeUnit;

public class ChatHandler {

    public static void execute(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame msg) {
        try {
            //解析前端发送过来的消息
            ChatMessage chat = JSON.parseObject(msg.text(),ChatMessage.class);
            switch (MessageType.match(chat.getType())){
                case PRIVATE:
                    //私聊并且目标存在的时候
                    if(StringUtil.isNullOrEmpty(chat.getTarget())){
                        channelHandlerContext.channel().writeAndFlush(Result.fail("发送失败，请确定目标对象是否存在"));
                        return;
                    }
                    Channel channel = NettyServer.USERS.get(chat.getTarget());
                    if(null == channel || !channel.isActive()){
                        channelHandlerContext.channel().writeAndFlush(Result.fail("对方不在线"));
                    }else {
                        channel.writeAndFlush(Result.success("私聊消息（"+ chat.getNickname() + ")",chat.getContent()));
                    }
                    break;
                case GROUP:
                    NettyServer.GROUP.writeAndFlush(Result.success("群聊消息(" + chat.getNickname() + ")", chat.getContent()));
                    break;
                default:
                    channelHandlerContext.channel().writeAndFlush(Result.fail("不支持消息类型"));
            }
        }catch (Exception e){
            e.printStackTrace();
            channelHandlerContext.channel().writeAndFlush(Result.fail(e.getMessage()));
        }
    }
}
